package com.liliudong.template.generator.entity;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.FieldNameConstants;

import java.util.List;
import java.util.Map;

/**
 * 列
 *
 * @author ldli5
 * @date 2024/7/1-15:21
 */
@Data
@FieldNameConstants
@AllArgsConstructor
@NoArgsConstructor
public class Columns {

	private String columnName;
	private String columnType;
	private String columnComment;
	private String isNullable;
	private String columnKey;
	private String extra;

	/**
	 * 获取列名camel
	 *
	 * @return {@link String }
	 */
	public String getColumnNameCamel() {
		return StrUtil.toCamelCase(this.columnName);
	}

	public boolean isPrimaryKey() {
		return "PRI".equals(this.columnKey);
	}

	public boolean isNullable() {
		return "NO".equals(this.isNullable);
	}
	public boolean isAutoIncrement() {
		return "auto_increment".equals(this.extra);
	}

	public String getJavaType() {
		if (this.columnType.contains("bigint")) {
			return "Long";
		}
		if (this.columnType.contains("varchar")) {
			return "String";
		}
		if (this.columnType.contains("int")) {
			return "Integer";
		}
		if (this.columnType.contains("datetime")) {
			return "LocalDateTime";
		}
		if (this.columnType.contains("timestamp")) {
			return "LocalDateTime";
		}
		if (this.columnType.contains("date")) {
			return "LocalDate";
		}
		if (this.columnType.contains("time")) {
			return "LocalTime";
		}
		if (this.columnType.contains("text")) {
			return "String";
		}
		if (this.columnType.contains("tinyint")) {
			return "Byte";
		}
		if (this.columnType.contains("smallint")) {
			return "Short";
		}
		if (this.columnType.contains("mediumint")) {
			return "Integer";
		}
		if (this.columnType.contains("float")) {
			return "Float";
		}
		if (this.columnType.contains("double")) {
			return "Double";
		}
		if (this.columnType.contains("decimal")) {
			return "BigDecimal";
		}
		if (this.columnType.contains("blob")) {
			return "byte[]";
		}
		if (this.columnType.contains("boolean")) {
			return "Boolean";
		}
		// 如果没有匹配的类型，返回默认值
		return "String";
	}


	public static List<Columns> fromMaps(List<Map<String, Object>> maps) {
		return maps.stream()
				.map(item -> {
					String columnName = MapUtil.get(item, Fields.columnName, String.class);
					String columnType = MapUtil.get(item, Fields.columnType, String.class);
					String columnComment = MapUtil.get(item, Fields.columnComment, String.class);
					String isNullable = MapUtil.get(item, Fields.isNullable, String.class);
					String columnKey = MapUtil.get(item, Fields.columnKey, String.class);
					String extra = MapUtil.get(item, Fields.extra, String.class);
					return new Columns(columnName, columnType, columnComment, isNullable, columnKey, extra);
				}).toList();
	}
}
